package com.xiaoyy.app.extend.gateway.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.xiaoyy.app.extend.common.enums.AppApiEnum;
import com.xiaoyy.app.extend.common.vo.ZwwFrUserResVO;
import com.xiaoyy.app.extend.gateway.req.ZjzwwLoginReq;
import com.xiaoyy.app.extend.util.ZjzzwUtil;
import com.xiaoyy.core.common.enums.LoginTypeEnum;
import com.xiaoyy.core.common.exception.AppException;
import com.xiaoyy.core.common.vo.AppResponse;
import com.xiaoyy.core.common.vo.LoginVO;
import com.xiaoyy.core.common.vo.TokenVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 浙江政务网用户登入相关
 *
 * @author chenzh
 * @date 2018-08-17
 */
@RestController
@RequestMapping(value = "/other/sso/zjzww")
@Api(tags = "第三方登录管理")
public class ZjzwwLoginController {
    @Value("${system.config.alipay.app.url}")
    private String appUrl;
    @Value("${system.config.zjzww.fr.url}")
    private String frUrl;
    @Value("${system.config.zjzww.projectId}")
    private String projectId;
    @Value("${system.config.zjzww.projectSecret}")
    private String projectSecret;
    /**
     * 政务网登录（个人）
     */
    @PostMapping(value = "/login", produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "政务网登录（个人）", notes = "用户登录")
    public AppResponse<TokenVO> loginZjzww(@RequestBody @Validated ZjzwwLoginReq loginReq, @ApiIgnore HttpServletRequest request) {
        LoginVO loginVO=(LoginVO)Convert.convert(LoginVO.class, loginReq);

        //登录前校验
        if (StringUtils.isBlank(loginVO.getLoginKey())) {
            throw new AppException("登录票据不能为空！");
        }
        //登录类型
        if (StringUtils.isBlank(loginVO.getLoginType())){
            loginVO.setLoginType(LoginTypeEnum.zjzww.getType());
        }else if(!LoginTypeEnum.zjzww.getType().equalsIgnoreCase(loginVO.getLoginType())){
            throw new AppException("登录类型错误！");
        }

        loginVO= ZjzzwUtil.getZwUserInfo(loginVO,request);

        try {
            String body = HttpUtil.post(appUrl + AppApiEnum.ZJZWWLOGIN.getType(), JSON.toJSONString(loginVO));
            return JSON.parseObject(body, AppResponse.class);
        }catch (Exception e){
            return AppResponse.errorMsg("内部服务请求异常"+e.getMessage());
        }
    }

    /**
     * 政务网登录（法人）
     */
    @PostMapping(value = "/login_fr")
    @ApiOperation(value = "政务网登录（法人）", notes = "用户登录")
    public AppResponse<TokenVO> loginZjzww(@RequestParam Map<String, Object> paramMap,@ApiIgnore HttpServletRequest request, @ApiIgnore HttpServletResponse response) {
        LoginVO loginVO =new LoginVO();
        String gotoUrl=null;//默认值

        if (paramMap.get("ssoticket") != null) {
            String ssoTicket=paramMap.get("ssoticket").toString();
        }else{
            throw new AppException("登录票据不能为空");
        }
        if (paramMap.get("ssotoken") != null) {
            String ssoToken=paramMap.get("ssotoken").toString();
            loginVO.setLoginKey(ssoToken);
        }else{
            throw new AppException("政务网法人登录失效");
        }
        //登录类型
        if (StringUtils.isBlank(loginVO.getLoginType())){
            loginVO.setLoginType(LoginTypeEnum.zjzww.getType());
        }else if(!LoginTypeEnum.zjzww.getType().equalsIgnoreCase(loginVO.getLoginType())){
            throw new AppException("登录类型错误！");
        }
        //回调后跳转地址
        if (paramMap.get("goto") != null) {
            gotoUrl = paramMap.get("goto").toString();
        }else {
            throw new AppException("缺少goto参数");
        }

        /////以下两项暂时无用
        if (paramMap.get("sundata") != null) {
            String sunData=paramMap.get("sundata").toString();
        }
        if (paramMap.get("spappurl") != null) {
            String spAppUrl=paramMap.get("spappurl").toString();
        }
        //////

        //获取用户信息
        ZwwFrUserResVO frUser= ZjzzwUtil.getZwFrInfo(loginVO,request,frUrl,projectId,projectSecret);

        try {
            String body = HttpUtil.post(appUrl + AppApiEnum.ZJZWWFRLOGIN.getType(), JSON.toJSONString(frUser));
            System.out.println("body:"+body);
            JSONObject jsonObj = new JSONObject(body);
            if(jsonObj.getStr("code").equals("0")) {
                System.out.println("result:"+jsonObj.getStr("result"));
                TokenVO tokenvo=JSON.parseObject(jsonObj.getStr("result"), TokenVO.class);
                gotoUrl += "?accessToken=" + tokenvo.getAccessToken()+"&expireMinute=" + tokenvo.getExpireMinute();
                response.sendRedirect(gotoUrl);
                return AppResponse.success();
            }else{
                return AppResponse.errorMsg("内部服务请求返回失败");
            }
        }catch (Exception e){
            return AppResponse.errorMsg("内部服务请求异常"+e.toString());
        }
    }




}
